package com.inspur.jzsxxzx.config;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;

@ControllerAdvice
public class SessionExpiredHandler {
    
    @ExceptionHandler(IllegalStateException.class)
    public ModelAndView handleSessionExpired(HttpServletRequest request, 
                                           HttpServletResponse response) throws IOException {
        // 检查是否是AJAX请求
        String ajaxHeader = request.getHeader("X-Requested-With");
        boolean isAjax = "XMLHttpRequest".equals(ajaxHeader);
        
        if (isAjax) {
            // 对于AJAX请求，返回JSON响应
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            Writer writer = response.getWriter();
            writer.write("{\"error\":\"SESSION_EXPIRED\",\"message\":\"会话已过期，请重新登录\"}");
            writer.flush();
            return null;
        } else {
            // 对于普通请求，重定向到登录页
            ModelAndView mav = new ModelAndView("redirect:/login");
            return mav;
        }
    }
}